/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.barrientosjunior.blackup.action;

import br.com.barrientosjunior.blackup.MainManager;
import br.com.barrientosjunior.blackup.model.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import gnu.crypto.cipher.Serpent;

/**
 *
 * @author Junior
 */
public class ExecuteEncryptedBackupAction implements BackupAction, Runnable{
    MainManager manager = null;
    File file = null;

    public ExecuteEncryptedBackupAction(MainManager manager, File file) {
        this.manager = manager;
        this.file = file;
    }
    
    public void execute() throws IOException {
        java.io.File fromFile = new java.io.File(file.getPathOrigin());
        java.io.File toFile = new java.io.File(file.getPathDestiny());

        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            int bs = 16;
            byte[] buffer = new byte[bs];

            Serpent ser = new Serpent();
            Object k = ser.makeKey(file.getPass().getBytes(), 16);

            byte[] encryptBuffer = new byte[bs];

            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1){
                if(bytesRead < 16){
                    JOptionPane.showMessageDialog(null, String.valueOf(buffer) + "      " + bytesRead);
                }
                ser.encrypt(buffer, 0, encryptBuffer, 0, k, bs);
                to.write(encryptBuffer, 0, bytesRead);
            }
        } catch (InvalidKeyException ex) {
            Logger.getLogger(ExecuteEncryptedBackupAction.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
          if (from != null)
            try {
              from.close();
            } catch (IOException e) {
              ;
            }
          if (to != null)
            try {
              to.close();
            } catch (IOException e) {
              ;
            }
        }
    }

    public void run(){
        try {
            this.execute();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(manager.getMainFrame(),
                    ex.getMessage(),
                    "Erro de backup",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}
